package com.sell.sell.service.impl;

import com.sell.sell.domain.ProductInfo;
import com.sell.sell.dto.CartDTO;
import com.sell.sell.enums.ProductStatusEnum;
import com.sell.sell.enums.ResultEnum;
import com.sell.sell.mapper.ProductInfoMapper;
import com.sell.sell.sellexception.SellException;
import com.sell.sell.service.ProductInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ProductInfoServiceImpl implements ProductInfoService {
    @Resource
    private ProductInfoMapper productInfoMapper;

    @Override
    public ProductInfo findByProductId(String productId) {
        return productInfoMapper.findByProductId(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoMapper.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

//    @Override
//    public List<ProductInfo> findAll(Pageable pageable) {
//        return productInfoMapper.;
//    }

    @Override
    @Transactional
    public Integer addProduct(ProductInfo productInfo) {
        Integer row=productInfoMapper.addProduct(productInfo);
       return row;
    }

    @Override
    public void increseStock(List<CartDTO> cartDTOList) {

    }

    @Override
    @Transactional
    public void decreseStock(List<CartDTO> cartDTOList) {
        for(CartDTO cartDTO:cartDTOList){
            ProductInfo productInfo = productInfoMapper.findByProductId(cartDTO.getProductId());
            if(productInfo ==null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
            if(result<0){
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            productInfoMapper.addProduct(productInfo);
        }
    }
}
